<?php

/**
 * Created by PhpStorm.
 * User: osyun
 * Date: 2017/8/14
 * Time: 11:13
 */

namespace app\member_address\admin;

use app\admin\controller\Admin;
use app\member_address\model\Address as MemberAddressModel;
use app\common\builder\ZBuilder;
use app\common\controller\Common;

class Index extends Common
{
    public function __construct(){
        parent::__construct();
        define('isDel',2);
        defined('UID') or define('UID', is_signin());

        $this->projectid = 1;
    }

    /*
     * 添加收货地址
     * @param  openid      用户openid
     * @param  projectid   项目id
     * @param  province	  省
     * @param  city	      市
     * @param  district	  区县
     * @param  linkMan	  联系人姓名
     * @param  address	  详细地址
     * @param  mobile	  联系方式
     * @param  code	      邮编
     */
    public function addAddress(){

        $data = $this->getRequestData();

        $model = new MemberAddressModel();
        $validate =$model->validateDataAddress($data); //验证接受到的数据

        if($validate == 1){

            $data['createtime'] = date('Y-m-d H:i:s', time()); //数据创建的时间
            $result = Db::name('address')->insert($data);

            if($result != 1) {
                $this->error('', '添加数据失败', 0);
            }else{
                $this->error('','添加数据成功',0,$code = 1);
            }

        }

    }

    /*
     * 删除收货地址
     * @param ids  地址id  例 : 1,2,3
     * @param  openid        用户openid
     * @return 返回成功/失败提示
     */
    public function delAddress(){

        $request = $this->request;

        $where = array();
        $where['openid'] = $request->param('openid');
        $where['id'] = array('in',explode(',',$request->param('id')));
        $where['isdel'] = isDel;
        if(empty($where['openid']) || empty($where['id'])){


            outFormat('','openid不能为空/id不能为空',0);
        }

        //删除数据
        $model = new MemberAddressModel();
        $result = $model->delAddress($where);

        if($result){
            outFormat('','删除成功',0);
        }else{
            outFormat('','删除失败',0);
        }

    }

    /*
     * 修改收货地址
     * @param  id          地址id
     * @param  openid      用户openid
     * @param  province	  省
     * @param  city	      市
     * @param  district	  区县
     * @param  linkMan	  联系人姓名
     * @param  address	  详细地址
     * @param  mobile	  联系方式
     * @param  code	      邮编
     * @return 返回成功/失败提示
     */
    public function updateAddress(){

        $request = $this->request;

        $id = $request->param('id');
        if(empty($id)){
            $this->error('','地址id不能为空',0);
        }
        $data = $this->getRequestData(); //获取数据

        $model = new MemberAddressModel();
        $result =$model->validateDataAddress($data); //返回数据验证结果


        $where = array();
        $where['id'] = $id;
        $where['openid'] = $data['openid'];

        if($result) {

            $model = new MemberAddressModel();
            $result = $model->updateAddress($where, $data);

            if ($result) {
                outFormat('', '更新成功', 1);
            } else {
                outFormat('', '更新失败', 0);
            }
        }
    }


    /*
     * 设置为默认地址
     * @param   id        地址id
     * @param   openid    用户openid
     * @return 返回正确/失败提示
     */

    public function setDefaultAddress(){

        $request = $this->request;

        // 获取当前请求的id变量
        $where = array();
        $where['id'] = $request->param('id');
        $where['openid'] = $request->param('openid');


        if(empty($where['id']) || empty($where['openid'])){
            outFormats('','id/openid 不能为空',0);
        }


        $model = new MemberAddressModel();
        $result = $model->setDefaultAddress($where);

        if($result){
            outFormats('','设置默认地址成功',0,$code=1);
        }else{
            outFormats('','设置默认地址失败',0);
        }
    }
    /*
     * 后台编辑地址/和设置默认地址
     */
    public function edit($id = null){

        if ($id === null) $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $where = array();
            $where['id'] = $this->request->param('id');
            $where['openid'] = $this->request->param('openid');
            $isdefault = $this->request->param('isdefault');

            if(empty($where['id']) || empty($where['openid'])){
                $this->error('','id/openid 不能为空',0);
            }

            if($isdefault == 'on'){
                $data['isdefault'] = 2;
            }else{
                $data['isdefault'] = 1;
            }

            $model = new MemberAddressModel();
            $result = $model->setDefaultAddress($where,$data);
            //echo $result;
            //echo $model->getLastSql();
            if($result){
                //outFormats('','设置默认地址成功',0,$code=1);
                $this->success('编辑成功',cookie('__forward__'));
            }else{
                $this->error('编辑失败');
            }


        }

        $where = array();
        $where['id'] = $this->request->param('id');
        $where['openid'] = $this->request->param('openid');


        $info = MemberAddressModel::where($where)->find();
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('设置默认地址') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'id'],
                ['hidden','openid'],

                ['text','linkMan', '收货人'],
                ['text','mobile', '联系电话'],
                ['text','province', '省'],
                ['text','city', ''],
                ['text','district','区县'],
                ['text','address','详细地址'],
            ])
            ->addSwitch('isdefault', '是否设置为默认地址', '', '1', ['color' => 'danger'])
            ->setFormData($info) // 设置表单数据
            ->fetch();

    }

    /*
     * 获取默认地址
     * @return 返回和地址相关的数组
     * @param  id             地址id
     * @return 返回默认地址信息
     *
     */

    public function getDefaultAddress(){

        $request = $this->request;

        $where = array();
        $where['openid'] = $request->param('openid');
        $where['projectid'] = $request->param('projectid');
        $where['isDefault'] = 1;
        $where['isdel'] = isDel;



        if(empty($where['openid']) || empty($where['projectid'])){
            outFormats('','openid/projectid不能为空',0);
        }

        $model = new MemberAddressModel();

        //获取默认地址
        $result =  $model->getDefaultAddress($where);


        if($result){
            outFormats($result,'ok',1,1);
        }else{
            outFormats('','未获取默认地址',0);
        }
    }

    /*
     * 获取地址列表
     * @param          id             地址id
     * @param          openid        用户openid
     * @param          province	     省
     * @param          city	         市
     * @param          district	     区县
     * @param          linkMan	     联系人姓名
     * @param          address	     详细地址
     * @param          mobile	     联系方式
     * @param          code	         邮编
     * @return 返回获取的地址列表
     */

    public  function getAddressList(){

        $request = $this->request;

        $where = array();
        $where['openid'] = $request->param('openid');        //用户openid
        $where['projectid'] = $request->param('projectid');     //项目id
        $page_number = $request->param('page_number');   //页码
        $page_size = $request->param('page_size');    //页面大小
        $where['isdel'] = isDel;


        if(empty($where['openid']) || empty($where['projectid'])){
            outFormats('','openid/projectid不能为空',0);
        }

        $model = new MemberAddressModel();

        $table = 'address';
        $fields = 'id,openid,province,city,district,linkMan,address,mobile,code';
        $result = $model->getByWhereList($table,$where,$fields,'id',$page_number,$page_size);

        if(count($result)==0){
            outFormats('','未获得地址数据',0);
        }else{
            outFormats($result,'获取地址数据成功',1,1);
        }
    }
    /*
     * 后台地址列表显示
     */
    public  function getAddress(){

        $request = $this->request;

        $where = array();
        $where['isdel'] = isDel;

        $model = new MemberAddressModel();

        $table = 'address';
        $fields = 'id,openid,province,city,district,linkMan,address,mobile,code,isdefault';
        //$result = $model->getByWhereList($table,$where,$fields,'id',$page_number,$page_size);
        $result = $model->getList($table,$where,$fields);


        $btn_access = [
            'title' => '设置默认地址',
            'icon'  => 'fa fa-fw fa-plus-square',
            'href'  => url('edit', ['id' => '__id__','openid'=>'__openid__'])
        ];

        if(count($result)==0){
            $this->error('未获得地址数据');
        }else{
            return ZBuilder::make('table')
                ->setPageTitle('地址管理')// 设置页面标题
                ->setTableName('address')// 设置数据表名
                ->setSearch(['id' => 'ID', 'linkMan' => '收货人'])// 设置搜索参数
                ->addColumn('isdefault', '状态', 'status', '', [1 => '默认地址:danger', 2=>'非默认地址:danger'])
                ->addColumns([ // 批量添加列
                    ['id', 'ID'],
                    ['linkMan', '收货人'],
                    ['mobile', '联系电话'],
                    ['province', '省'],
                    ['city', '市'],
                    ['district','区县'],
                    ['address','详细地址'],
                    //['isdefault', '默认地址',[1=>'默认收货地址:danger',2=>'非默认']],
                    ['right_button', '操作', 'btn']
                ])
                ->addTopButtons('add,delete')
                ->addRightButton('custom', $btn_access) // 添加授权按钮
                ->setPages($result->render())
                ->setRowList($result)// 设置表格数据
                ->fetch(); // 渲染页面

        }

    }


    /*
     * 获取请求数据
     */
    private function getRequestData(){

        $request = $this->request;

        $data = array();

        $data['openid'] = $request->param('openid');          //用户openid
        $data['projectid'] = $request->param('projectid');    //项目id
        $data['province'] = $request->param('province');	  //省
        $data['city'] = $request->param('city');              //市
        $data['district'] = $request->param('district');	  //区县
        $data['linkMan'] = $request->param('linkMan');	      //联系人姓名
        $data['address'] = $request->param('address');	      //详细地址
        $data['mobile'] = $request->param('mobile');	      //联系方式
        $data['code'] = $request->param('code');              //邮编

        return $data;
    }
}